from collections.abc import Generator
from typing import Annotated

import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jwt.exceptions import InvalidTokenError
from pydantic import ValidationError
from sqlmodel import Session

from app.core import security
from app.core.config import settings
from app.core.db import engine
from app.model.models import TokenPayload, User

reusable_oauth2 = OAuth2PasswordBearer(
    tokenUrl=f"{settings.API_V1_STR}/login/access-token"
)


def get_db() -> Generator[Session, None, None]:
    with Session(engine) as session:
        yield session


SessionDep = Annotated[Session, Depends(get_db)]
TokenDep = Annotated[str, Depends(reusable_oauth2)]


def get_current_user(session: SessionDep, token: TokenDep) -> User:
    """
    从会话和令牌中获取当前用户。
    
    Args:
        session (SessionDep): 数据库会话依赖项。
        token (TokenDep): JWT 令牌依赖项。
    
    Returns:
        User: 当前用户对象。
    
    Raises:
        HTTPException: 
            - 403: 如果令牌无效或无法验证凭据。
            - 404: 如果用户不存在。
            - 400: 如果用户未激活。
    """
    try:
        payload = jwt.decode(
            token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
        )
        token_data = TokenPayload(**payload)
    except (InvalidTokenError, ValidationError):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Could not validate credentials",
        )
    user = session.get(User, token_data.sub)
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    if not user.is_active:
        raise HTTPException(status_code=400, detail="Inactive user")
    return user

"""
定义一个类型别名 `CurrentUser`，表示当前已验证的用户对象。

该类型别名使用 `Annotated` 和 `FastAPI` 的 `Depends` 机制，
依赖 `get_current_user` 函数获取当前用户实例。

通常用于 FastAPI 路由中，自动注入当前用户信息。
"""
CurrentUser = Annotated[User, Depends(get_current_user)]



def get_current_active_superuser(current_user: CurrentUser) -> User:
    if not current_user.is_superuser:
        raise HTTPException(
            status_code=403, detail="The user doesn't have enough privileges"
        )
    return current_user
